import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {ProduceService} from "../share/produce.service";

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  formModel:FormGroup;

  constructor(
    private produceService :ProduceService
  ) {
    //以后用响应式表单的验证就用fb.
    let fb = new FormBuilder();
    this.formModel = fb.group({
      title: ['',Validators.minLength(3)],//Validators.minLength 是自带的表单验证 最少长度验证
      price:[null,this.positiveNumberVaildator],//自定义的验证
      category:['-1']
    })
  }
  categories : string[];
  ngOnInit() {
    let fb = new FormBuilder();
    console.log(fb);
    this.categories=this.produceService.getAllCategories()
  }
  positiveNumberVaildator(control: FormControl) :any{
    //如果没有值 那么返回空
    if(!control.value){
      return null;
    }
    let price =parseInt(control.value);
    if(price > 0){
      return null;
    }else{
      //如果输入的值不对 那么返回true
      return {number: true}
    }
  }
  onSearch(){
    if(this.formModel.valid){
      // console.log(this.formModel.value)
      this.produceService.searchEvent.emit(this.formModel.value)
    }
  }
}
